# This file shows mongrel doing db with asymy with fibers [note the fibers are started in the fibered mongrel file
# to test:
#  ab -n 10 -c 10 http://127.0.0.1:3000/
#  you should see interleaved 'small' and 'big' messages when it starts, then all the small finish, then all the big [representing large DB queries]
#
# note: requires patched evented_mongrel [currently]
#
require 'rubygems'
require 'swiftcore/evented_mongrel'
require File.dirname(__FILE__) + '/fibered_mongrel'
require File.dirname(__FILE__) + '/../../source/asymy/asymy'
require File.dirname(__FILE__) + '/asymy_fiber_stop'
require File.dirname(__FILE__) + '/../setup_db_opts'
#print EM::kqueue# -- unstable ugh
EM::epoll # stable

 class SimpleHandler < Mongrel::HttpHandler
    @@count_ever = 0
    def process(request, response)
      # note that @'s here are shared among mongrel's incoming connections!--don't use them
      my_count = @@count_ever
      @@count_ever += 1
      response.start(200) do |head,out|
        head["Content-Type"] = "text/plain"
        out.write("hello!\n")

      	conn = Asymy::Connection.new $opts
      	1.times { |n|
      	   local_var = nil # an example of how to set local vars :)
      	   size = [:small, :big][my_count % 2]
      	   query = "select count(*) from #{ size == :small ? 'users' : 'user_sessions' }"
      	   print "starting #{my_count} #{size} #{n}\n"
           a = conn.exec_and_fiber_yield(query) {|h, c| local_var = [h,c]} # a == local_var at this point
           print "done #{my_count} #{size} #{n}\n"
      	}
      	conn.em_connection.close_connection # I added this one :)
      end
    end
 end

 h = Mongrel::HttpServer.new("0.0.0.0", 3000)
 h.register("/", SimpleHandler.new)
 h.register("/files", Mongrel::DirHandler.new("."))
 h.run.join
